package com.c2b.algorithm.leetcode.jzoffer;

/**
 * <a href="https://leetcode.cn/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/description/">在排序数组中查找数字</a>
 * <p>统计一个数字在排序数组中出现的次数。</p>
 * <pre>
 * 示例 1:
 *      输入: nums = [5,7,7,8,8,10], target = 8
 *      输出: 2
 *
 * 示例 2:
 *      输入: nums = [5,7,7,8,8,10], target = 6
 *      输出: 0
 * </pre>
 *
 * @author c2b
 * @since 2023/4/6 19:06
 */
public class JzOffer0053Search_I {

    /**
     * 思路：通过二分找到最左侧的target，然后向右遍历
     */
    public int search(int[] nums, int target) {
        int res = 0;
        if (nums == null || nums.length == 0) {
            return res;
        }
        int leftIndex = 0;
        int rightIndex = nums.length - 1;
        int mid;
        // 找出数组中「第一个等于target 的位置」
        while (leftIndex < rightIndex) {
            mid = leftIndex + ((rightIndex - leftIndex) >> 1);
            if (nums[mid] >= target) {
                rightIndex = mid;
            } else {
                leftIndex = mid + 1;
            }
        }
        // 不断向右寻找，直到越界或数组中的值与目标值不等
        while (rightIndex < nums.length && nums[rightIndex] == target) {
            ++rightIndex;
            ++res;
        }
        return res;
    }

    public static void main(String[] args) {
        JzOffer0053Search_I jzOffer0053Search_i = new JzOffer0053Search_I();
        System.out.println(jzOffer0053Search_i.search(new int[]{5, 7, 7, 8, 8}, 6));
    }
}
